package com.shenyue.nbtownlet.activity;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.SearchView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.adapter.LabelListViewAdapter;
import com.shenyue.nbtownlet.adapter.ViewPagerAdapter;
import com.shenyue.nbtownlet.base.BaseActivity;
import com.shenyue.nbtownlet.base.BaseFragment;
import com.shenyue.nbtownlet.databinding.ActivityContactsBinding;
import com.shenyue.nbtownlet.databinding.AreaViewBinding;
import com.shenyue.nbtownlet.event.BaseListener;
import com.shenyue.nbtownlet.fragment.DutySupervisorFragment;
import com.shenyue.nbtownlet.fragment.LeaderIntroduceFragment;
import com.shenyue.nbtownlet.fragment.OrganizationIntroduceFragment;
import com.shenyue.nbtownlet.fragment.OrganizationPersonnelFragment;
import com.shenyue.nbtownlet.helper.BottomNavigationViewHelper;
import com.shenyue.nbtownlet.model.AppLoginModel;
import com.shenyue.nbtownlet.model.AppModel;
import com.shenyue.nbtownlet.model.AppContactsModel;
import com.shenyue.nbtownlet.util.DensityUtil;
import com.shenyue.nbtownlet.util.NetWorkUtils;
import com.shenyue.nbtownlet.util.StringUtil;

/**
 * 通讯录
 */
public class ContactsActivity extends BaseActivity implements BottomNavigationView.OnNavigationItemSelectedListener, View.OnClickListener, AdapterView.OnItemClickListener {
    private ActivityContactsBinding binding;
    private Context mContext;
    private ViewPagerAdapter viewPagerAdapter;
    private Handler mHandler = new Handler();
    private int menu_type = 0;
    private SearchView searchView;
    private AreaViewBinding areaViewBinding;
    private MenuItem searchMenu;
    private BottomSheetDialog areaSheetDialog;
    private LabelListViewAdapter countyListViewAdapter, streetListViewAdapter;
    private boolean isAreaLoading = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_contacts);
        setActionBar(true, getString(R.string.tv_contacts));
        mContext = this;

        binding.navigation.setOnNavigationItemSelectedListener(this);
        BottomNavigationViewHelper.disableShiftMode(binding.navigation);
        //设置icon的大小
        BottomNavigationMenuView menuView = (BottomNavigationMenuView) binding.navigation.getChildAt(0);
        for (int i = 0; i < menuView.getChildCount(); i++) {
            final View iconView = menuView.getChildAt(i).findViewById(android.support.design.R.id.icon);
            final ViewGroup.LayoutParams layoutParams = iconView.getLayoutParams();
            layoutParams.height = DensityUtil.dip2px(mContext, 18);
            layoutParams.width = DensityUtil.dip2px(mContext, 18);
            iconView.setLayoutParams(layoutParams);
        }
        setupViewPager(binding.viewpager);

        AppModel.setStreetId(mContext, null);
        AppModel.setAreaId(mContext, null);

        setArea();
    }

    private void setupViewPager(ViewPager viewPager) {
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.addFragment(OrganizationIntroduceFragment.newInstance(getString(R.string.tv_organization_introduce)));
        viewPagerAdapter.addFragment(LeaderIntroduceFragment.newInstance(getString(R.string.tv_leader_introduce)));
        viewPagerAdapter.addFragment(OrganizationPersonnelFragment.newInstance(getString(R.string.tv_organization_personnel)));
        viewPagerAdapter.addFragment(DutySupervisorFragment.newInstance(getString(R.string.tv_duty_supervisor)));

        viewPager.setOffscreenPageLimit(viewPagerAdapter.getCount());
        viewPager.setAdapter(viewPagerAdapter);
        viewPager.setCurrentItem(2, false);

        setSelectedItemId(2);
    }

    private void changePage(final int position) {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                binding.viewpager.setCurrentItem(position, false);
                String title = viewPagerAdapter.getPageItemTitle(position);
                setActionBarTitle(title);
            }
        }, 32);
    }

    public void setSelectedItemId(int position) {
        BaseFragment fragment = viewPagerAdapter.getCurrentFragment();
        if (fragment != null)
            fragment.willBeDisplayed();

        binding.navigation.getMenu().getItem(position).setChecked(true);
        changePage(position);
        //修改菜单
        switch (position) {
            case 0:
                setActionBarMenu(0);
                break;
            case 1:
                setActionBarMenu(0);
                break;
            case 2:
                setActionBarMenu(1);
                break;
            case 3:
                setActionBarMenu(1);
                break;
        }

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                BaseFragment fragment = viewPagerAdapter.getCurrentFragment();
                if (fragment != null) {
                    fragment.refresh(null);
                }
            }
        }, 32);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        if (!NetWorkUtils.isExistNetwork(mContext))
            return false;
        switch (item.getItemId()) {
            case R.id.btn_organization_introduce:
                setSelectedItemId(0);
                return true;
            case R.id.btn_leader_introduce:
                setSelectedItemId(1);
                return true;
            case R.id.btn_organization_personnel:
                setSelectedItemId(2);
                return true;
            case R.id.btn_duty_supervisor:
                setSelectedItemId(3);
                return true;
        }
        return false;
    }

    private void setActionBarMenu(int menu_type) {
        this.menu_type = menu_type;
        invalidateOptionsMenu();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (menu != null)
            menu.clear();
        if (menu_type == 1) {
            getMenuInflater().inflate(R.menu.contacts_menu, menu);
            searchMenu = menu.findItem(R.id.action_search);
            searchView = (SearchView) searchMenu.getActionView();
            searchView.setQueryHint("请输入名称检索");
            setSearchView();
        }

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        hideSearchView();
        switch (item.getItemId()) {
            case R.id.btn_001: {//区域选择
                areaSheetDialog.show();
                if (isAreaLoading)
                    break;
                queryCountyList();
                break;
            }
            case R.id.btn_002: {//人员查询
                searchMenu.expandActionView();
                break;
            }
            case R.id.btn_003: {//收藏列表
                BaseFragment fragment = viewPagerAdapter.getCurrentFragment();
                if (fragment != null) {
                    JSONObject param = new JSONObject();
                    param.put("collect", true);
                    fragment.refresh(param);
                }
                break;
            }
            case R.id.btn_all: {//全部
                BaseFragment fragment = viewPagerAdapter.getCurrentFragment();
                if (fragment != null) {
                    JSONObject param = new JSONObject();
                    param.put("all", true);
                    fragment.refresh(param);
                }
                break;
            }
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setSearchView() {
        if (this.searchView != null) {
            EditText searchPlate = (EditText) this.searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
            if (searchPlate == null)
                return;
            searchPlate.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        BaseFragment fragment = viewPagerAdapter.getCurrentFragment();
                        if (fragment != null) {
                            JSONObject param = new JSONObject();
                            param.put("people", true);
                            param.put("name", searchView.getQuery().toString());
                            fragment.refresh(param);
                        }
                    }
                    return false;
                }
            });
        }
    }

    private void hideSearchView() {
        if (this.searchMenu != null)
            this.searchMenu.collapseActionView();
    }

    private void setArea() {
        areaViewBinding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.area_view, null, false);
        areaSheetDialog = new BottomSheetDialog(this);
        areaSheetDialog.setContentView(areaViewBinding.getRoot());
        areaSheetDialog.setCancelable(false);
        areaSheetDialog.setCanceledOnTouchOutside(false);
        areaViewBinding.btnOk.setOnClickListener(this);
        areaViewBinding.btnCancel.setOnClickListener(this);
        countyListViewAdapter = new LabelListViewAdapter(mContext);
        areaViewBinding.county.setAdapter(countyListViewAdapter);
        areaViewBinding.county.setOnItemClickListener(this);

        streetListViewAdapter = new LabelListViewAdapter(mContext);
        areaViewBinding.street.setAdapter(streetListViewAdapter);
        areaViewBinding.street.setOnItemClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_cancel:
                areaSheetDialog.hide();
                break;
            case R.id.btn_ok: {
                areaSheetDialog.hide();
                setAreaId();
                BaseFragment fragment = viewPagerAdapter.getCurrentFragment();
                if (fragment != null) {
                    JSONObject param = new JSONObject();
                    fragment.refresh(param);
                }
                break;
            }
        }
    }

    private void setAreaId() {
        JSONArray countyList = countyListViewAdapter.getItems();
        for (int i = 0, j = countyList.size(); i < j; i++) {
            JSONObject item = (JSONObject) countyList.get(i);
            if (item.getBooleanValue("selected")) {
                AppModel.setAreaId(mContext, StringUtil.dTs(item.getString("ID")));
                break;
            }else
                AppModel.setAreaId(mContext, null);
        }
        JSONArray streetList = streetListViewAdapter.getItems();
        for (int i = 0, j = streetList.size(); i < j; i++) {
            JSONObject item = (JSONObject) streetList.get(i);
            if (item.getBooleanValue("selected")) {
                AppModel.setStreetId(mContext, StringUtil.dTs(item.getString("ID")));
                break;
            }else
                AppModel.setStreetId(mContext, null);
        }

        for (int i = 0, j = viewPagerAdapter.getCount(); i < j; i++) {
            viewPagerAdapter.getItem(i).setLoading(false);
        }
    }

    private void queryCountyList() {
        JSONObject param = new JSONObject();
        param.put("areaid", AppModel.getNingBoAreaID(mContext));
        param.put("areaidByIdentity", AppLoginModel.getAreaId(mContext));
        AppContactsModel.GetNextLevelAreaID(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                isAreaLoading = true;
                countyListViewAdapter.clear();
                countyListViewAdapter.addItems(JSON.parseArray(val));
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    private void queryStreetList(String areaid) {
        JSONObject param = new JSONObject();
        param.put("areaid", areaid);
        param.put("areaidByIdentity", AppLoginModel.getAreaId(mContext));
        AppContactsModel.GetNextLevelAreaID(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                streetListViewAdapter.clear();
                streetListViewAdapter.addItems(JSON.parseArray(val));
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent == areaViewBinding.county) {
            JSONArray countyList = countyListViewAdapter.getItems();
            for (int i = 0, j = countyList.size(); i < j; i++) {
                JSONObject item = (JSONObject) countyList.get(i);
                item.put("selected", false);
            }
            JSONObject item = (JSONObject) countyList.get(position);
            item.put("selected", true);
            countyListViewAdapter.notifyDataSetChanged();
            queryStreetList(StringUtil.dTs(item.getString("ID")));
        } else if (parent == areaViewBinding.street) {
            JSONArray streetList = streetListViewAdapter.getItems();
            for (int i = 0, j = streetList.size(); i < j; i++) {
                JSONObject item = (JSONObject) streetList.get(i);
                item.put("selected", false);
            }
            JSONObject item = (JSONObject) streetList.get(position);
            item.put("selected", true);
            streetListViewAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        AppModel.setStreetId(mContext, null);
        AppModel.setAreaId(mContext, null);
    }
}
